package com.oceansoft.mobile.biz.front.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.weixin.entity.WxToken;
import com.oceansoft.mobile.weixin.service.WechatService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.weixin.entity.WX_User;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

/**
 * Created by Administrator on 2016/1/20.
 */
@Controller
@RequestMapping("oauth")
public class OauthController {

    @Resource
    private ICommonDao commonDao;
    @Resource
    private WechatService wechatService;

    @RequestMapping(value = "oauth")
    public String oauth(HttpServletRequest request, Model model) {
        String redirectUrl = Constant.REDIRECTURL;
        String state = request.getParameter("state");
        String merid = (String) request.getSession().getAttribute("merid");
        WxToken wxToken = WeixinUtil.loadTokenByMerid(merid);
        if (StringUtils.hasText(merid)) {
            if (state.indexOf("?") > 10) {
                state += "&merid=" + merid;
            } else {
                state += "?merid=" + merid;
            }
        }
        String url = "";
        try {
            url = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//		try {
//			state = URLEncoder.encode(state, "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} 
        StringBuilder stringBuilder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
        stringBuilder.append("appid=").append(wxToken.getAppid())
                .append("&redirect_uri=").append(url)
                .append("&response_type=code&scope=").append("snsapi_base")
                .append("&state=" + state)
                //.append(userState)
                .append("#wechat_redirect");
        System.out.println(stringBuilder.toString());
        return "redirect:" + stringBuilder.toString();//正式环境
//       return "redirect:" +  Constant.REDIRECTURL+"?state="+state;//测试环境
    }

    @RequestMapping(value = "oauth2")
    public String oauth2(HttpServletRequest request, Model model) {
        String state = request.getParameter("state");
        //从配置项目中读取到对应state的页面
        String pageName = Constant.stateMap.get(state);
        if (!StringUtils.hasText(pageName)) {
            pageName = Constant.stateMap.get("0");
        }

        String merid = (String) request.getSession().getAttribute("merid");
        WxToken token = WeixinUtil.loadTokenByMerid(merid);

        String openId = WeixinUtil.getOpenId(request);
//	   开发环境中session中拿
//	   String openId = (String) request.getSession().getAttribute("openId");
//	   openId = "ol7bHt_mUn8pl0C0EOQhYQY0jsOA";
        System.out.println("oauth2--------获取到用户openID===" + openId);


        int exist = 0;//本地数据库未绑定省厅openid

        WX_User user = commonDao.loadOne("select * from wx_user t where t.openid=? and t.subscribe=1", WX_User.getMapp(), openId);
        if (null == user && !"1070".equals(merid)) {
            //去官网在验证一下
            user = WeixinUtil.getUserInfoMer(openId, merid);
//		   System.out.println("官网在验证一下==="+user);
//		   System.out.println(user.getSubscribe()==1);
            if (null != user && user.getSubscribe() == 1) {
                System.out.println("+++++++++++++++++++++:2++" + user.getSubscribe());
//			   System.out.println("官网在验证一下===用户信息===="+user.getSubscribe());
                //保存用户信息到数据库
                user.setWx_openid(token.getOpenid());
                user.setCreate_time(new Date());
                commonDao.saveOne("INSERT INTO wx_user (subscribe,openid,nickname,sex,city,country,province,language,headimgurl,subscribe_time,wx_openid,create_time,unionid) VALUES(:subscribe,:openid,:nickname,:sex,:city,:country,:province,:language,:headimgurl,:subscribe_time,:wx_openid,:create_time,:unionid) ",
                        user);
            } else {
                    System.out.println("+++++++++++++++++++++:3+++" + user.getSubscribe());
            }
        }

        if (state.startsWith("http://") || state.startsWith("http://")) {
//		   state  = state.indexOf("?")>-1?state:state+"?1=1";
            pageName = state;
        }

        if (user != null) {
            if (!"".equals(user.getSubscribe())) {
                if (user.getSubscribe() == 0) {
                    //用户没有关注，去关注
                    if (merid.equals("1070")) {
                        pageName = Constant.stateMap.get("-1");
                    } else if (merid.equals("1069")) {
                        pageName = Constant.stateMap.get("-2");
                    }

                }
            }
        }
        System.out.println("oauthcontroller-------StringUtils.hasText(openId)"+StringUtils.hasText(openId));
        if (StringUtils.hasText(openId)) {
            if (merid.equals("1070")) {
                request.getSession().setAttribute("openIdwjw", openId);
            } else if (merid.equals("1069")) {
                System.out.println("==user.getSubscribe()=="+user.getSubscribe());
                if (user != null) {
                    if (!"".equals(user.getSubscribe())) {
                        if (user.getSubscribe() == 0) {
                            //用户没有关注，去关注
                            if (merid.equals("1070")) {
                                pageName = Constant.stateMap.get("-1");
                            } else if (merid.equals("1069")) {
                                pageName = Constant.stateMap.get("-2");
                            }
                            System.out.println("去关注");
                        }else {
                            request.getSession().setAttribute("openIdjf", openId);
                            System.out.println("已关注");
                        }
                    }
                }

            }
//            request.getSession().setAttribute("openId", openId);
        }

        //TODO 没有openid需要去关注页面
//        else {
//            pageName = Constant.stateMap.get("-1");
//        }
        if (pageName.startsWith("http://") || state.startsWith("http://")) {
            pageName = "redirect:" + pageName;
            if (pageName.indexOf("?") > 10) {
                pageName += "&openId=" + openId;
            } else {
                pageName += "?openId=" + openId;
            }
        }
        if (StringUtils.hasText(openId)) {
            //openId="ol7bHt3lvDtzFms5Fr5RqKwGHn2c";
           /* if (exist == 0) {
                HttpSession session = request.getSession();
                session.setAttribute("wxOpenid", openId);
                session.setAttribute("pageName", pageName);
                try {
                    String judgeUrl = Constant.host5 + "api/User/GetOtherIDbyOpenID2?openid=" + openId;
                    String rs = HttpClientUtil.doGet(judgeUrl);
                    System.out.println("======判断这个用户是否已在网厅绑定了省厅的OPENID：" + rs);
                    JSONObject jsonObject = JSONObject.fromObject(rs);
                    if (jsonObject.get("succ").toString().equals("true")) {
                        if (jsonObject.get("data").toString().equals("2")) {
                            user = WeixinUtil.getUserInfoMer(openId, merid);
                            Map<String, String> param = new HashMap<String, String>();
                            param.put("OPENID", user.getOpenid());
                            param.put("NICKNAME", user.getNickname());
                            param.put("SEX", user.getSex() + "");
                            param.put("CITY", user.getCity());
                            param.put("COUNTRY", user.getCountry());
                            param.put("PROVINCE", user.getProvince());
                            param.put("LANGUAGE", user.getLanguage());
                            param.put("HEADIMGURL", user.getHeadimgurl());
                            param.put("SUBSCRIBE_TIME", user.getSubscribe_time() + "");
                            param.put("UNIONID", user.getUnionid());
                            param.put("SUBSCRIBE", user.getSubscribe() + "");
                            param.put("SYNC_STATE", "0");
                            param.put("APP_ID",token.getSt_appid());
                            param.put("APP_KEY",token.getSt_appsecret());
                            param.put("SZQX",user.getWx_openid());
                            String uploadUrl = Constant.host5 + "api/User/InsertWXUser2";
                            String rst = HttpClientUtil.doPost(uploadUrl, param, "utf-8");
                            System.out.println("========将没有同步的用户存入网厅的result=====:" + rst);
                        }
                        if (!jsonObject.get("data").toString().equals("0")) {
                            String accessToken = wechatService.getSTAccessToken(merid);
                            System.out.println("=======省厅accessToken：" + accessToken);
                            String url = WeixinUtil.getSTOpenId(openId,token.getSt_appid(), accessToken);
                            System.out.println("=======省厅授权URL：" + url);
                            return "redirect:" + url;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
        }


        System.out.println("oauthoauthoauth==pageName===" + pageName);
        return pageName;
    }

    @RequestMapping(value = "oauth3")
    public String oauth3(HttpServletRequest request, Model model) {
        String st_openId = request.getParameter("st_open_id");
        String err_code = request.getParameter("err_code");
        String err_msg = request.getParameter("err_msg");
        System.out.println("=====省厅OPENID：" + st_openId);
        System.out.println("=====省厅err_code：" + err_code);
        System.out.println("=====省厅err_msg：" + err_msg);
        HttpSession session = request.getSession();
        String merid = session.getAttribute("merid").toString();
        if (!"".equals(err_msg) && null != err_msg) {
            try {
                CacheBaseService.getInstance().delCache("ST_ACCESSTOKEN:" + merid);
                String access = wechatService.getSTAccessToken(merid);
                System.out.println("======省厅accessToken过期，重新获取：" + access);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String openId = session.getAttribute("wxOpenid").toString();
        if (!"".equals(st_openId) && null != st_openId) {
            String updateUrl = Constant.host5 + "api/user/updateWXUser2";
            Map<String, String> param = new HashMap<String, String>();
            param.put("OPENID", openId);
            param.put("ST_OPENID", st_openId);
//            String res = HttpClientUtil.doPostString(updateUrl, param);
            String res = HttpClientUtil.doPost(updateUrl, param, "utf-8");
            System.out.println("=========省厅OPENID更新到网厅：" + res);
            WX_User user = new WX_User();
            user.setOpenid(openId);
            user.setSt_openid(st_openId);
            commonDao
                    .updateOne(
                            "UPDATE wx_user t set t.st_openid = :st_openid  where t.openid = :openid",
                            user);
            System.out.println("======省厅OPENID更新到本地数据库");
        }
        String pageName = session.getAttribute("pageName").toString();
        return pageName;
    }

    private static String getClientIP(HttpServletRequest request) {
        String fromSource = "X-Real-IP";
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
            fromSource = "X-Forwarded-For";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            fromSource = "Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            fromSource = "WL-Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            fromSource = "request.getRemoteAddr";
        }
        //client.info("App Client IP: "+ip+", fromSource: "+fromSource);
        return ip;
    }

    @RequestMapping(value = "getOpenId")
    public String getOpenId(HttpServletRequest request) {
//		Result result =new Result();
        String openId = (String) request.getSession().getAttribute("openId");//
        String page = request.getParameter("page");
        if (StringUtils.isEmpty(page)) {
            return Constant.stateMap.get("0");
        } else {
            if (!page.startsWith("http")) {
                page = "http://" + page;
            }
        }
        String source = request.getParameter("source");
        if (!StringUtils.isEmpty(source)) {
            request.getSession().setAttribute("source", source);
        }

        //存在openId  直接跳转
        if (!StringUtils.isEmpty(openId)) {
//			System.out.println("getOpenId === "+  page + "?openId = " + openId );
            String pageRetuen = page;
            if (page.contains("?")) {
                pageRetuen += "&openId=" + openId;
            } else {
                pageRetuen += "?openId=" + openId;
            }

            return "redirect:" + pageRetuen;
        } else {
            //去微信后台拿
            String u = Constant.local + "oauth/oauth?state=" + page;

//            System.out.println("getOpenId=="+u);
            return "redirect:" + u;
        }
    }


}
